﻿using System.Linq;
using Microsoft.SharePoint;
using Trentacular.SharePoint.Deployment.Model;
using Trentacular.SharePoint.Deployment.Util;

namespace Trentacular.SharePoint.Deployment.Data.Proxy
{
    public class WebFeaturesLazyInitializer : BaseDomainListLazyInitializer<Web, WebFeature>
    {
        protected override object InitializeTarget()
        {
            using (var spSite = new SPSite(Owner.Site.Id))
            {
                using (var spWeb = spSite.OpenWeb(Owner.Id))
                {
                    var activatedFeatures = spWeb.Features
                        .Cast<SPFeature>()
                        .Select(f => f.DefinitionId)
                        .ToList();

                    return Owner.Site.WebApplication.AvailableFeatureDefinitions
                        .Where(fd => fd.Scope == SPFeatureScope.Web)
                        .Select(fd => new WebFeature
                            {
                                Definition = fd,
                                Parent = Owner,
                                Activated = activatedFeatures.Contains(fd.Id)
                            })
                        .ToVirtualList();
                }
            }
        }
    }
}
